package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.IweChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Service
public class WeChatServiceImpl implements IweChatService {


    @Value("${weChat.appId}")
    private String appid;
    @Value("${weChat.appSecret}")
    private String secret;
private String OPENID_URL="https://api.weixin.qq.com/sns/jscode2session";
    private String PHONE_URL="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private String TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token";
    @Override
    public String getPhone(String phoneCode) {
        Map paramMap =new HashMap();
        paramMap.put("code",phoneCode);
        HttpResponse response = HttpUtil.createRequest(Method.POST, PHONE_URL+token()).body(JSONUtil.toJsonStr(paramMap)).execute();


        if (response.isOk()){
            String body = response.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            String phone = jsonObject.getByPath("phone_info.phoneNumber",String.class);
            return phone;
        }
        return null;

    }

    private String token() {
        Map paramMap =new HashMap();
        paramMap.put("appid",appid);
        paramMap.put("secret",secret);
        paramMap.put("grant_type","client_credential");
        HttpResponse response = HttpUtil.createRequest(Method.GET, TOKEN_URL).form(paramMap).execute();


        if (response.isOk()){
            String body = response.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            String token = jsonObject.getStr("access_token");
            return token;
        }
        return null;
    }

    @Override
    public String getOpenid(String code) {
        Map paramMap =new HashMap();
        paramMap.put("appid",appid);
        paramMap.put("secret",secret);
        paramMap.put("js_code",code);
        paramMap.put("grant_type","authorization_code");
        HttpResponse response = HttpUtil.createRequest(Method.GET, OPENID_URL).form(paramMap).execute();


        if (response.isOk()){
            String body = response.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            String openid = jsonObject.getStr("openid");
            return openid;
        }
        return null;
    }
}
